package handlers

import (
	"go-ddd-ecommerce/internal/application/dto"
	"go-ddd-ecommerce/internal/application/services"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type ProductController struct {
	productService *services.ProductAppService
}

func NewProductController(productService *services.ProductAppService) *ProductController {
	return &ProductController{productService: productService}
}

type CreateProductRequest struct {
	Name  string  `json:"name" binding:"required"`
	Price float64 `json:"price" binding:"required,min=0"`
	Stock int     `json:"stock" binding:"required,min=0"`
}

type GetProductRequest struct {
	ProductID string `json:"product_id" binding:"required"`
}

// 创建商品
func (pc *ProductController) CreateProduct(c *gin.Context) {
	var req CreateProductRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.CreateProductDTO{
		Name:  req.Name,
		Price: req.Price,
		Stock: req.Stock,
	}

	product, err := pc.productService.CreateProduct(cmd)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"message": "产品创建成功",
		"product": product,
	})
}

// 获取所有商品
func (pc *ProductController) GetProducts(c *gin.Context) {
	products, err := pc.productService.GetProducts()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, products)
}

// 获取单个商品
func (pc *ProductController) GetProduct(c *gin.Context) {
	var req GetProductRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.GetProductByIDDTO{
		ProductId: uuid.MustParse(req.ProductID),
	}

	product, err := pc.productService.GetProductByID(cmd)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "未找到产品"})
		return
	}

	c.JSON(http.StatusOK, product)
}
